layui.define(['element', 'upload', 'layerPlus'], function(exports) {
  var element = layui.element
    , layer = layui.layerPlus
    , upload = layui.upload
    , $ = layui.jquery
    , files = {}
    , uploadListIns = {}
    , uploadConfigs = {};

  var defaultConfig = {
    id: '',// 当页面有多个按钮时，唯一区分每个上传按钮
    target: '',// 绑定的div
    tips: '', // 提示性文字
    accept: 'file', // 接收的文件类型，默认全部
    multiple: true, // 是否可选择多文件，默认开启
    data: {}, // 上传时提交的额外数据
    download: path + 'api/sysDocFile/download/', // 文件下载链接
    preview: '', // 预览文件的链接
    url: path + 'api/sysDocFile/upload', // 文件上传链接
    dataUrl: '', // 赋值请求
    defaultValue: [], //默认值
    mode: '', // 上传组件的模式，若为view，则不显示按钮
  };

  var ksUpload = {
    config: {},
    getFiles: function(id) {
      return files[id];
    },
    setFiles: function(id, data) {
      var _config = uploadConfigs[id];
      _config.defaultValue = data;
      if(_config.multiple === true) {
        initMultipleValue(_config)
      } else {
        initSingleValue(_config.defaultValue[0], _config)
      }
    },
    render: function(properties) {
      var id = properties.id;
      if(uploadConfigs[id]) { // 重新渲染
        this.config = $.extend(true, {}, uploadConfigs[id], properties);
      } else {
        this.config = $.extend(true, {}, defaultConfig, properties);
      }
      var _config = this.config
        , target = _config.target;
      if(!target || $(target)[0].tagName.toLowerCase() !== 'div' || $(target).length > 1) {
        layer.msg.warn('每次只能绑定单个div元素');
        return;
      }
      var html;
      files[id] = [];
      uploadConfigs[id] = _config;
      if(_config.multiple === true) {
        // 没有初始化过才初始化
        if($('#fileList-' + id).length === 0) {
          html = [
            '<div class="layui-upload>',
            '  <div class="layui-btn-group" id="btnGroupDiv">',
            '    <button type="button" class="layui-btn layui-btn-normal" id="uploadBtn-' + id + '">',
            '      <i class="layui-icon">&#xe621;</i>选择文件',
            '    </button>',
            '    <button type="button" class="layui-btn" id="uploadAction-' + id + '">',
            '      <i class="layui-icon">&#xe681;</i>开始上传',
            '    </button>',
            '  </div>',
          ];

          if(_config.tips) {
            html.push(
              '  <div class="layui-word-aux" style="line-height: 38px;">',
              _config.tips,
              '  </div>'
            );
          }
          html.push(
            '  <div class="layui-upload-list">',
            '    <table class="layui-table">',
            '      <thead>',
            '      <tr>',
            '        <th>文件名</th>',
            '        <th>大小</th>',
            '        <th>状态</th>',
            '        <th>操作</th>',
            '      </tr>',
            '      </thead>',
            '      <tbody id="fileList-' + id + '">',
            '      </tbody>',
            '    </table>',
            '  </div>',
            '</div>');
          $(target).html(html.join(''));

          if(_config.mode !== 'view') {
            _config.auto = false;
            _config.elem = '#uploadBtn-' + id;
            _config.bindAction = '#uploadAction-' + id;
            _config.progress = function(n, index, elem) {
              var percent = n + '%'; //获取进度百分比
              // console.log(elem);
              element.progress('process-' + id + '-' + index, percent);
            };
            _config.choose = function(obj) {
              //将每次选择的文件追加到文件队列
              var files = this.files = obj.pushFile();
              //读取本地文件
              obj.preview(function(index, file, result) {
                var tr = $([
                  '<tr id="upload-' + id + '-' + index + '">',
                  '  <td>' + file.name + '</td>',
                  '  <td>' + (file.size / 1014).toFixed(1) + 'kb</td>',
                  '  <td>',
                  '    <div class="layui-progress" lay-showPercent="yes" lay-filter="process-' + id + '-' + index + '">',
                  '      <div class="layui-progress-bar layui-bg-green" lay-percent="0%"></div>',
                  '    </div>',
                  '  </td>',
                  '  <td>',
                  '    <a class="layui-btn layui-btn-xs btn-reload layui-hide">重传</a>',
                  (_config.preview ? '    <a class="layui-btn layui-btn-xs btn-view layui-btn-normal layui-hide">查看</a>' : ''),
                  '    <a class="layui-btn layui-btn-xs btn-down layui-hide">下载</a>',
                  '    <a class="layui-btn layui-btn-xs layui-btn-danger btn-delete">删除</a>',
                  '  </td>',
                  '</tr>'].join(''));

                //单个重传
                tr.find('.btn-reload').on('click', function() {
                  obj.upload(index, file);
                });

                //删除
                tr.find('.btn-delete').on('click', function() {
                  delete files[index]; //删除对应的文件
                  tr.remove();
                  //清空 input file 值，以免删除后出现同名文件不可选
                  uploadListIns[id].config.elem.next()[0].value = '';
                });

                $('#fileList-' + id).append(tr);
                element.render('progress');
              });
            };
            _config.done = function(res, index, upload) {
              if(res.code === 200) { //上传成功
                var tr = $('#fileList-' + id).find('tr#upload-' + id + '-' + index)
                  , tds = tr.children()
                  , file = res.data
                  , filePath = _config.download + file.id;
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                if(_config.filePreview) {
                  var filePreview = _config.preview.replace('{filePath}', filePath).replace('{id}', file.id);
                  //文件预览
                  tds.eq(3).find('.btn-view').on('click', function() {
                    window.open(filePreview);
                  });
                  tds.eq(3).find('.btn-view').removeClass('layui-hide'); //显示查看
                }
                var $downBtn = tds.eq(3).find('.btn-down');
                $downBtn.attr('href', filePath);
                $downBtn.attr('download', file.name);
                $downBtn.removeClass('layui-hide'); //显示下载
                files[id].push(res.data);
                return delete this.files[index]; //删除文件队列已经上传成功的文件
              }
              this.error(index, upload);
            };
            _config.error = function(index, upload) {
              var tr = $('#fileList-' + id).find('tr#upload-' + index)
                , tds = tr.children();
              tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
              tds.eq(3).find('.btn-reload').removeClass('layui-hide'); //显示重传
            };
            uploadListIns[id] = upload.render(_config);
          } else {
            $('#btnGroupDiv').remove();
            $('.btn-reload').remove();
            $('.btn-delete').remove();
          }
        }
        // 初始化数据
        if(_config.defaultValue.length > 0) {
          initMultipleValue(_config)
        }
      } else {
        if($('#fileArea-' + id).length === 0) {
          html = [
            '<button type="button" class="layui-btn layui-btn-normal" id="uploadBtn-' + id + '" style="float: left">',
            '  <i class="layui-icon">&#xe621;</i>选择文件',
            '</button>',
            '<div class="layui-row" id="fileArea-' + id + '" style="float: left;margin-left: 10px">',
            '</div>'
          ].join('');
          $(target).html(html);
          _config.elem = '#uploadBtn-' + id;
          _config.done = function(res) {
            if(res.code === 200) { //上传成功
              var file = res.data;
              initSingleValue(file, _config);
            } else {
              layer.msg.sad('调用接口出错');
            }
          };
          _config.error = function(index, upload) {
            layer.msg.error('发生错误', function() {
              $('#fileArea-' + id).html('');
            });
          };
          uploadListIns[id] = upload.render(_config);
        }

        if(_config.defaultValue) {
          var val = _config.defaultValue;
          if(val instanceof Array) {
            if(val.length > 0) initSingleValue(val[0], _config)
          } else {
            initSingleValue(val, _config)
          }
        }
      }

    }
  };

  function initSingleValue(file, _config) {
    var id = _config.id
      , filePath = _config.download + file.id
      , filePreview = _config.preview.replace('{filePath}', filePath).replace('{id}', file.id)
      , fileArea = [
      '<a href="' + filePath + '" target="_blank">' + file.name + '</a>&emsp;',
    ];
    if(filePreview === 'img') {
      fileArea = ['<img src="' + filePath + '" style="width: 160px;height: 160px"/>']
    } else if(filePreview) {
      fileArea.push('<a class="layui-btn layui-btn-sm" href="' + filePreview + '" target="_blank">查看</a>');
    }
    $('#fileArea-' + id).html(fileArea.join(''));
    files[id][0] = file;
  }

  function initMultipleValue(_config) {
    var fileList = _config.defaultValue
      , id = _config.id;
    layui.each(fileList, function(index, file) {
      files[id].push(file);
      var filePath = _config.download + file.id
      var tr = $([
        '<tr id="upload-' + id + '-' + index + '">',
        '  <td>' + file.name + '</td>',
        '  <td>' + (file.fileSize / 1014).toFixed(1) + 'kb</td>',
        '  <td>已完成</td>',
        '  <td>',
        (_config.filePreview ? '    <a class="layui-btn layui-btn-xs btn-view layui-btn-normal">查看</a>' : ''),
        '    <a class="layui-btn layui-btn-xs btn-down" href="' + filePath + '" download="' + file.name + '">下载</a>',
        (_config.mode !== 'view' ? '    <a class="layui-btn layui-btn-xs layui-btn-danger btn-delete">删除</a>' : ''),
        '  </td>',
        '</tr>'
      ].join(''));
      if(_config.mode !== 'view') {
        //删除
        tr.find('.btn-delete').on('click', function() {
          tr.remove();
        });
      }

      if(_config.filePreview) {
        var filePreview = _config.preview.replace('{filePath}', filePath).replace('{id}', file.id);
        //查看
        tr.find('.btn-view').on('click', function() {
          window.open(filePreview);
        });
      }

      $('#fileList-' + id).append(tr);
    });
  }

  exports('ksUpload', ksUpload)
});
